package com.tongcao.cn.aspect;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @Author:tongcao
 * @Date:2018/8/25 18:01
 * Description:
 */
@Slf4j
@Aspect
@Component
public class TaskAopAdvice {

    @Pointcut("execution(* com.tongcao.cn.task.*.execute(..))")
    public void pointCut_(ProceedingJoinPoint joinPoint) {

    }

    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        StopWatch clock = new StopWatch();
        clock.start(); //计时开始
        Object obj = pjp.proceed();
        clock.stop();  //计时结束

        String methodName = pjp.getSignature().getName();

        long time = clock.getTime();

        // 超过指定时间时记录到另外一个文件中
        if (time >= 2000L) {
            String className = pjp.getSignature().getDeclaringTypeName();
            StringBuilder sb = new StringBuilder(200);
            String title = className + "." + methodName;
            sb.append(className).append(",").append(methodName);
            // 添加方法的参数, 方便调试
            Object[] params = pjp.getArgs();
            if (params != null && params.length > 0) {
                StringBuilder sbParam = new StringBuilder();
                for (Object param : params) {
                    if (param == null) {
                        continue;
                    }
                    sbParam.append(",").append(param.getClass().getSimpleName()).append("=");
                    if (param.getClass().isPrimitive() || param instanceof String) {
                        sbParam.append(param);
                    } else {
                        sbParam.append(JSON.toJSONString(param));
                    }
                }
                if (sbParam.length() > 0) {
                    sb.append(sbParam.substring(1));
                }
            }
            log.info(title + sb.toString());
        }
        return obj;
    }
}
